#include "netservice.h"
#include <thread>
#include <sstream>
#include <stdlib.h>

namespace cores
{
    namespace services
    {
        namespace v1
        {
            NetService::NetService(const string& serviceName) : BaseService(serviceName), Publisher("net_service")
            {}

            NetService::~NetService()
            {}

            void NetService::init()
            {

            }

            void NetService::start()
            {
                _running = true;
                thread recvThread([this] {this->run();});
                recvThread.detach();
            }

            void NetService::stop()
            {}

            void NetService::run()
            {
                while (_running)
                {
                    // 检测网络是否连通
                    if (_netIsConnected == false)
                    {
                        _netIsConnected = checkNetwork();
                    }

                    if (_netIsConnected == false)
                    {
                        _netIsConnected = connectNetwork();
                    }

                    if (_netIsConnected)
                    {
                        doWork();
                    }

                    this_thread::sleep_for(chrono::milliseconds(50));
                }
            }

            bool NetService::checkNetwork()
            {
                stringstream ss;
                ss << "ping -c " << 1 /*<< " -i " << 1*/ << " www.baidu.com";
                if (system(ss.str().c_str()) == 0)
                    return true;

                return false;
            } 

            bool NetService::connectNetwork()
            {
                
            }

            void NetService::doWork()
            {
                // 启动4G模块
            }
        }
    }
}